package com.anysoft.service;

import android.content.Context;
import android.os.Environment;

import com.blankj.utilcode.util.FileUtils;
import com.anysoft.MentorApplication;
import com.anysoft.bean.AppInfo;
import com.anysoft.me.config.CommentConfig;
import com.anysoft.utils.OpenFileTipDialog;

import java.io.File;

/**
 * Created by lty on 2017/12/10.
 */

public class DownloadFileHelper {

    private static DownloadFileHelper helper;
    private Context mContext;
    private File mDownloadDir;

    public DownloadFileHelper() {
        mContext = MentorApplication.context;
        mDownloadDir = Environment.getExternalStoragePublicDirectory(CommentConfig.DOWNLOAD_DIR_NAME);
        FileUtils.createOrExistsDir(mDownloadDir);
    }

    public static DownloadFileHelper getInstence() {
        if (helper == null) {
            helper = new DownloadFileHelper();
        }
        return helper;
    }

    public void downloadStart(int position, AppInfo appInfo) {
        if (appInfo.getStatus() == AppInfo.STATUS_DOWNLOADING || appInfo.getStatus() == AppInfo.STATUS_CONNECTING) {
            pause(appInfo.getUrl());
        } else if (appInfo.getStatus() == AppInfo.STATUS_COMPLETE) {
            install(appInfo);
        } else {
            download(position, appInfo.getUrl(), appInfo);
        }
    }


    private void download(int position, String tag, AppInfo info) {
        DownloadService.intentDownload(mContext, position, tag, info);
    }

    private void pause(String tag) {
        DownloadService.intentPause(mContext, tag);
    }

    private void install(AppInfo appInfo) {
        OpenFileTipDialog.openFiles(new File(mDownloadDir, appInfo.getName()).getAbsolutePath(), mContext);
    }

}
